package com.example.gokuplayalong.service.fragments.main;

import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.MainActivity;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.baiduapi.BaiduApi;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.custom.CustomGlideEngine;
import com.example.gokuplayalong.bases.custom.CustomImageUtils;
import com.example.gokuplayalong.bases.custom.textwatcher.RegExUtil;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.NetWorkInterface;
import com.example.gokuplayalong.bases.network.updown.Upload;
import com.example.gokuplayalong.bases.network.updown.UploadDownInterface;
import com.example.gokuplayalong.bases.permission.PermissionUtils;
import com.example.gokuplayalong.bases.permission.PermissionUtilsInterface;
import com.example.gokuplayalong.bases.tools.Logger;
import com.example.gokuplayalong.bases.tools.Tools;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileApplication;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileBalanceDetail;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileMerchantInfo;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileMoreSetting;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileOnlineCustom;
import com.example.gokuplayalong.service.fragments.users.receive.UserMainReceiveUserInfo;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialogx.interfaces.OnInputDialogButtonClickListener;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.engine.CropFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import pub.devrel.easypermissions.AppSettingsDialog;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserMainProfile#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class UserMainProfile extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    View rootView;

    MessageDialog messageDialog;

    public static int uploadSuccessFlag = 0;
    private ImageView mUserMainProfileHeadshot;
    private TextView mUserMainProfileNickname;
    private TextView mUserMainProfileNicknameChange;
    private TextView mUserMainProfileUserid;
    private TextView mUserMainProfilePhone;
    private TextView mUserMainProfileBalanceDetail;
    private TextView mUserMainProfileBalance;
    private TextView mUserMainProfileUnfrozen;
    private TextView mUserMainProfileFrozen;
    private LinearLayout mUserMainProfileApplication;
    private TextView mUserMainProfileApplicationShow;
    private LinearLayout mUserMainProfileMyorder;
    private LinearLayout mUserMainProfilePersoninfo;
    private LinearLayout mUserMainProfileOnlineCustom;
    private LinearLayout mUserMainProfileMoreSetting;

    public UserMainProfile() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserMainProfile.
     */
    // TODO: Rename and change types and number of parameters
    public static UserMainProfile newInstance(String param1, String param2) {
        UserMainProfile fragment = new UserMainProfile();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_user_main_profile, container, false);
        initView();
        return rootView;
    }

    private void initView() {

        mUserMainProfileHeadshot = rootView.findViewById(R.id.user_main_profile_headshot);
        mUserMainProfileNickname = rootView.findViewById(R.id.user_main_profile_nickname);
        mUserMainProfileNicknameChange = rootView.findViewById(R.id.user_main_profile_nickname_change);
        mUserMainProfileUserid = rootView.findViewById(R.id.user_main_profile_userid);
        mUserMainProfilePhone = rootView.findViewById(R.id.user_main_profile_phone);
        mUserMainProfileBalanceDetail = rootView.findViewById(R.id.user_main_profile_balance_detail);
        mUserMainProfileBalance = rootView.findViewById(R.id.user_main_profile_balance);
        mUserMainProfileUnfrozen = rootView.findViewById(R.id.user_main_profile_unfrozen);
        mUserMainProfileFrozen = rootView.findViewById(R.id.user_main_profile_frozen);
        mUserMainProfileApplication = rootView.findViewById(R.id.user_main_profile_application);
        mUserMainProfileApplicationShow = rootView.findViewById(R.id.user_main_profile_application_show);
        mUserMainProfileMyorder = rootView.findViewById(R.id.user_main_profile_myorder);
        mUserMainProfilePersoninfo = rootView.findViewById(R.id.user_main_profile_personinfo);
        mUserMainProfileOnlineCustom = rootView.findViewById(R.id.user_main_profile_online_custom);
        mUserMainProfileMoreSetting = rootView.findViewById(R.id.user_main_profile_more_setting);


        mUserMainProfilePersoninfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchOnSysFragment("UserMainProfileInfo");
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileBalanceDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchOnSysFragment("UserMainProfileBalanceDetail");
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileMoreSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchOnSysFragment("UserMainProfileMoreSetting");
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileNicknameChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;

                    new InputDialog("提示", "输入新名字", "确定", "取消", "").setCancelable(false)
                            .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                                @Override
                                public boolean onClick(InputDialog baseDialog, View v, String inputStr) {

                                    BaiduApi.textCensor(RegExUtil.regexString(inputStr), new Handler(Looper.myLooper()) {
                                        @Override
                                        public void handleMessage(@NonNull Message msg) {
                                            super.handleMessage(msg);
                                            switch (msg.what) {
                                                case 1: {
                                                    Beans beansIn = new Beans();
                                                    beansIn.getJsonObject()
                                                            .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                    .getString("phone"));
                                                    beansIn.getJsonObject()
                                                            .put("nickname", RegExUtil.regexString(inputStr));
                                                    AppParams.getNewNetWork()
                                                            .setInterface(new NetWorkInterface() {
                                                                @Override
                                                                public int success(String msg) {
                                                                    requireActivity().runOnUiThread(new Runnable() {
                                                                        @Override
                                                                        public void run() {
                                                                            try {
                                                                                JSONObject msgFromServer = JSON.parseObject(msg);
                                                                                if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                                                                    mUserMainProfileNickname.setText(RegExUtil.regexString(inputStr));
                                                                                    AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                                            .put("nickname", RegExUtil.regexString(inputStr));
                                                                                    PopTip.show("修改成功！");
                                                                                }
                                                                            } catch (Throwable e) {

                                                                            }
                                                                        }
                                                                    });
                                                                    return 0;
                                                                }

                                                                @Override
                                                                public int failed(String msg) {
                                                                    return 0;
                                                                }
                                                            })
                                                            .execute(AppParams.getInstance().baseUrl + "/modifyNickName", beansIn.getJsonObject()
                                                                    .toJSONString());


                                                }
                                                break;
                                                case 2: {
                                                    PopTip.show("名称不合规");
                                                }
                                                break;
                                            }
                                        }
                                    });


                                    return false;
                                }
                            })
                            .show();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });

        mUserMainProfileApplication.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    if (AppParams.getInstance().appCurrentUser.getJsonObject()
                            .getIntValue("merchantcertify") == 1) {
                        SysManagerFragments.switchOnSysFragment("UserMainProfileMerchantInfo");
                    }
                    else {
                        SysManagerFragments.switchOnSysFragment("DirectPayMerchantCreate");
                    }
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileMyorder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchOnSysFragment("UserMainProfileMyOrder");
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });


        mUserMainProfileOnlineCustom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchOnSysFragment("UserMainProfileOnlineCustom");
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileHeadshot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Tools.Deshak()) return;
                try {
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
                        PermissionUtils.getInstance()
                                .checkPermission(PermissionUtils.permission_storage_sdk33, "悟空陪玩正在申请存储权限，用于上传截图、证明等，是否继续？", PermissionUtils.requestCode_storage_sdk33, new PermissionUtilsInterface() {
                                    @Override
                                    public void hasPermissions() {
                                        page2GkUpload();
                                    }

                                    @Override
                                    public void onPermissionsGranted(int i, @NonNull List<String> list) {
                                        page2GkUpload();
                                    }

                                    @Override
                                    public void onPermissionsDenied(int i, @NonNull List<String> list) {
                                        PopTip.show("权限被拒绝");
                                        new AppSettingsDialog.Builder(MainActivity.getInstance()).setTitle("无存储权限")
                                                .setRationale("\"悟空陪玩\"需要存储权限才能正常运行，打开设置界面开启存储权限")
                                                .setPositiveButton("去设置")
                                                .setNegativeButton("退出")
                                                .build()
                                                .show();

                                    }
                                });

                    }
                    else {
                        PermissionUtils.getInstance()
                                .checkPermission(PermissionUtils.permission_storage, "悟空陪玩正在申请存储权限，用于上传截图、证明等，是否继续？", PermissionUtils.requestCode_storage, new PermissionUtilsInterface() {
                                    @Override
                                    public void hasPermissions() {
                                        page2GkUpload();
                                    }

                                    @Override
                                    public void onPermissionsGranted(int i, @NonNull List<String> list) {
                                        page2GkUpload();
                                    }

                                    @Override
                                    public void onPermissionsDenied(int i, @NonNull List<String> list) {
                                        PopTip.show("权限被拒绝");
                                        new AppSettingsDialog.Builder(MainActivity.getInstance()).setTitle("无存储权限")
                                                .setRationale("\"悟空陪玩\"需要存储权限才能正常运行，打开设置界面开启存储权限")
                                                .setPositiveButton("去设置")
                                                .setNegativeButton("退出")
                                                .build()
                                                .show();
                                    }
                                });

                    }
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }


            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        initResume();
    }

    private void initResume() {
        try {
            if (AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getIntValue("merchantcertify") == 1) {
                mUserMainProfileApplicationShow.setText("我的店铺");
            }
            else {
                mUserMainProfileApplicationShow.setText("申请成为陪玩人员");
            }
            String filename = AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getString("phone") + "_headshot_upload.png";


            if (uploadSuccessFlag == 0) {
                Picasso.with(MainActivity.getInstance())
                        .load(AppParams.getInstance().uploadMediaLocationServer + "/" + filename)
//                        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                        .networkPolicy(NetworkPolicy.NO_CACHE)
                        .into(mUserMainProfileHeadshot);
            }
            else if (uploadSuccessFlag == -1) {
                uploadSuccessFlag = 0;
                Picasso.with(MainActivity.getInstance())
                        .load(AppParams.getInstance().uploadMediaLocationServer + "/" + filename)
                        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                        .networkPolicy(NetworkPolicy.NO_CACHE)
                        .into(mUserMainProfileHeadshot);
            }
            mUserMainProfilePhone.setText(AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getString("phone"));
            mUserMainProfileUserid.setText(AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getString("userid"));
            mUserMainProfileNickname.setText(AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getString("nickname"));
            mUserMainProfileBalance.setText(String.format("%s", AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getDoubleValue("unfrozen") + AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getDoubleValue("frozen")));
            mUserMainProfileUnfrozen.setText(String.format("未冻结%s元", AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getDoubleValue("unfrozen")));
            mUserMainProfileFrozen.setText(String.format("已冻结%s元", AppParams.getInstance().appCurrentUser.getJsonObject()
                    .getDoubleValue("frozen")));

        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    private void page2GkUpload() {
        try {

            PictureSelector.create(MainActivity.getInstance())
                    .openGallery(SelectMimeType.ofImage())

                    .setCompressEngine((CompressFileEngine) ((context, source, call) -> {
                        Luban.with(context)
                                .load(source)
                                .setCompressListener(new OnNewCompressListener() {
                                    @Override
                                    public void onStart() {
                                        Logger.d("onStart");
                                    }

                                    @Override
                                    public void onSuccess(String source, File compressFile) {
                                        Logger.d("onSuccess");
                                        if (call != null) {
                                            call.onCallback(source, compressFile.getAbsolutePath());
                                        }
                                    }

                                    @Override
                                    public void onError(String source, Throwable e) {
                                        Logger.d("onError " + e.getMessage());
                                        if (call != null) {
                                            call.onCallback(source, null);
                                        }
                                    }
                                }).launch();
                    }))
                    .isDisplayCamera(false)
                    .setMaxSelectNum(1)
                    .setCropEngine(new CropFileEngine() {
                        @Override
                        public void onStartCrop(Fragment fragment, Uri srcUri, Uri destinationUri, ArrayList<String> dataSource, int requestCode) {
                            try {
                                UCrop.of(srcUri, destinationUri)
                                        .withAspectRatio(1, 1)
                                        .start(fragment.requireContext(), fragment, requestCode);
                            } catch (Throwable e) {
                                ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                            }
                        }
                    })
                    .setImageEngine(CustomGlideEngine.createGlideEngine())
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            if (!result.isEmpty()) {
                                LocalMedia localMedia = (LocalMedia) result.get(0);

                                BaiduApi.imageEncodedCensor(CustomImageUtils.encodeImageToBase64(new File(localMedia.getCompressPath())), new Handler(Looper.myLooper()) {
                                    @Override
                                    public void handleMessage(@NonNull Message msg) {
                                        super.handleMessage(msg);
                                        switch (msg.what) {
                                            case 1: {
                                                String filename = AppParams.getInstance().appCurrentUser.getJsonObject()
                                                        .getString("phone") + "_headshot_upload.png";

                                                Upload.getInstance()
                                                        .uploadImage(new File(localMedia.getCompressPath()), localMedia.getMimeType(), filename, new UploadDownInterface() {
                                                            @Override
                                                            public void uploadSuccess(String msg) {
                                                                requireActivity().runOnUiThread(new Runnable() {
                                                                    @Override
                                                                    public void run() {
                                                                        try {
                                                                            uploadSuccessFlag = 1;
                                                                            PopTip.show("上传成功!");
                                                                            Picasso.with(MainActivity.getInstance())
                                                                                    .load(AppParams.getInstance().uploadMediaLocationServer + "/" + filename)
                                                                                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                                                                                    .networkPolicy(NetworkPolicy.NO_CACHE)
                                                                                    .into(mUserMainProfileHeadshot);
                                                                        } catch (Throwable e) {
                                                                            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                                        }
                                                                    }
                                                                });
                                                            }

                                                            @Override
                                                            public void uploadFailed(IOException e) {
                                                                PopTip.show("上传失败!");
                                                            }

                                                            @Override
                                                            public void downSuccess() {

                                                            }

                                                            @Override
                                                            public void downFailed() {

                                                            }
                                                        });

                                            }
                                            break;
                                            case 2: {
                                                PopTip.show("图片不合规，请重新上传!");
                                            }
                                            break;
                                        }
                                    }
                                });

                            }
                        }

                        @Override
                        public void onCancel() {

                        }
                    });

        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }
}